﻿using CalligraphyEditor.CalligraphyData;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace CalligraphyEditor.ViewModel
{
    public class VMPaperPhotos
    {
        private T_StelePaper _stelePaper;

        private CollectionViewSource _cvs;
        public CollectionViewSource Cvs
        {
            get { return _cvs; }
        }

        private ObservableCollection<T_PaperPhoto> _ocl;

        public VMPaperPhotos(T_StelePaper stelePaper)
        {
            _stelePaper = stelePaper;
            var q = from sp in CalligraphyEditor.App.Entities.T_PaperPhoto.Expand("T_Photo").Expand("T_StelePaper") where sp.StelePaperID == stelePaper.ID && (sp.IsDeleted == null || sp.IsDeleted == false) orderby sp.PageNumber ascending select sp;
            _ocl = new ObservableCollection<T_PaperPhoto>(q);
            _cvs = new CollectionViewSource();
            _cvs.Source = _ocl;            
        }

        public void Delete()
        {
            if (_ocl.Count == 0)
                return;
            foreach (var pp in _ocl)
            {
                pp.IsDeleted = true;
                CalligraphyEditor.App.Entities.UpdateObject(pp);

            }
            CalligraphyEditor.App.Entities.SaveChanges();
            _ocl.Clear();
        }

        public void Upload()
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                return;
            var photoPaths = System.IO.Directory.GetFiles(dialog.SelectedPath, "*.jpg", System.IO.SearchOption.TopDirectoryOnly);
            var txtPaths = System.IO.Directory.GetFiles(dialog.SelectedPath, "*.txt", System.IO.SearchOption.TopDirectoryOnly);
            var photoNumsFilePaths = PhotoHelper.FilePathsToNums(photoPaths);
            var txtNumsFilePaths = PhotoHelper.FilePathsToNums(txtPaths);

            

            foreach (var photoKey in photoNumsFilePaths.Keys)
            {
                var photo = PhotoHelper.UploadPhoto(photoNumsFilePaths[photoKey]);
                T_PaperPhoto pp = new T_PaperPhoto();
                pp.T_Photo = photo;
                pp.PhotoID = photo.ID;
                pp.PageNumber = photoKey;
                pp.StelePaperID = _stelePaper.ID;
                pp.T_StelePaper = _stelePaper;
                pp.Text = PhotoHelper.GetText(photoKey, txtNumsFilePaths);
                _stelePaper.T_PaperPhoto.Add(pp);
                CalligraphyEditor.App.Entities.AddToT_PaperPhoto(pp);
                CalligraphyEditor.App.Entities.SaveChanges();
                _ocl.Add(pp);
            }

        }
    }
}
